import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class MyHttpClient2 {

    public static void main(String[] args) throws IOException, InterruptedException {
        // 创建一个 HTTP 对象
        // 创建对象的时候使用工厂类
        HttpClient client = HttpClient.newHttpClient();

        // 这样 new 出来需要重写许多方法，非常的麻烦，有另一种构造 Http 请求的方法
    /*HttpRequest request = new HttpRequest() {
        @Override
        public Optional<BodyPublisher> bodyPublisher() {
            return Optional.empty();
        }

        @Override
        public String method() {
            return "";
        }

        @Override
        public Optional<Duration> timeout() {
            return Optional.empty();
        }

        @Override
        public boolean expectContinue() {
            return false;
        }

        @Override
        public URI uri() {
            return null;
        }

        @Override
        public Optional<HttpClient.Version> version() {
            return Optional.empty();
        }

        @Override
        public HttpHeaders headers() {
            return null;
        }
    }*/

        // 创建 request 使用工厂类
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://www.gitee.com"))
                .GET()
                .header("User-Agent","xxxx")
                .build();
        // 以 build 方法结尾

        // 发送请求，获取响应,且以 String 的格式处理响应
        // send 执行之后会阻塞等待，直到响应返回
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode());
        System.out.println(response.headers());
        System.out.println(response.body());
    }

}
